import 'dart:async';

import 'package:flutter/material.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/sound_record.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/manager/xindong_permission_ctr.dart';

class XinDongLiaoTianInputSound extends StatefulWidget {
  final Function(String path, int duration) send;
  final Widget? buttons;

  const XinDongLiaoTianInputSound({Key? key, required this.send, this.buttons}) : super(key: key);

  @override
  State<XinDongLiaoTianInputSound> createState() => _XinDongSendSoundMessageState();
}

class _XinDongSendSoundMessageState extends State<XinDongLiaoTianInputSound> {
  String soundTipsText = "";
  bool isRecording = false;
  bool isInit = false;
  bool isCancelSend = false;
  DateTime startTime = DateTime.now();
  List<StreamSubscription<Object>> subscriptions = [];

  OverlayEntry? overlayEntry;
  String voiceIcon = "images/voice_volume_1.png";

  buildOverLayView(BuildContext context) {
    if (overlayEntry == null) {
      overlayEntry = OverlayEntry(builder: (content) {
        soundTipsText = "手指上滑，取消发送";
        return Positioned(
          top: MediaQuery.of(context).size.height * 0.5 - 80,
          left: MediaQuery.of(context).size.width * 0.5 - 80,
          child: Material(
            type: MaterialType.transparency,
            child: Center(
              child: Opacity(
                opacity: 0.8,
                child: Container(
                  width: 160,
                  height: 160,
                  decoration: const BoxDecoration(
                    color: Color(0xff77797A),
                    borderRadius: BorderRadius.all(Radius.circular(20.0)),
                  ),
                  child: Column(
                    children: <Widget>[
                      Container(
                        margin: const EdgeInsets.only(top: 10),
                        child: Image.asset(
                          voiceIcon,
                          width: 100,
                          height: 100,
                          package: 'flutter_plugin_record_plus',
                        ),
                      ),
                      Text(
                        soundTipsText,
                        style: const TextStyle(
                          fontStyle: FontStyle.normal,
                          color: Colors.white,
                          fontSize: 14,
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      });
      Overlay.of(context).insert(overlayEntry!);
    }
  }

  onLongPressStart(_) {
    if (isInit) {
      startTime = DateTime.now();
      SoundPlayer.startRecord();
      buildOverLayView(context);
    }
  }

  onLongPressUpdate(e) {
    double height = MediaQuery.of(context).size.height * 0.5 - 240;
    double dy = e.localPosition.dy;
    if (dy.abs() > height) {
      if (mounted && soundTipsText != "松开取消") {
        setState(() {
          soundTipsText = "松开取消";
        });
      }
    } else {
      if (mounted && soundTipsText == "松开取消") {
        setState(() {
          soundTipsText = "手指上滑，取消发送";
        });
      }
    }
  }

  onLongPressEnd(e) {
    double dy = e.localPosition.dy;
    // 此高度为 160为录音取消组件距离顶部的预留距离
    double height = MediaQuery.of(context).size.height * 0.5 - 240;
    if (dy.abs() > height) {
      isCancelSend = true;
    } else {
      isCancelSend = false;
    }
    if (overlayEntry != null) {
      overlayEntry!.remove();
      overlayEntry = null;
    }
    // Did not receive onStop from FlutterPluginRecord if the duration is too short.
    if (DateTime.now().difference(startTime).inSeconds < 1) {
      isCancelSend = true;
      showToast("说话时间太短!");
    }
    stop();
  }

  onLonePressCancel() {
    if (isRecording) {
      isCancelSend = true;
      if (overlayEntry != null) {
        overlayEntry!.remove();
        overlayEntry = null;
      }
      stop();
    }
  }

  void stop() {
    setState(() {
      isRecording = false;
    });
    SoundPlayer.stopRecord();
    setState(() {
      soundTipsText = "手指上滑，取消发送";
    });
  }

  sendSound({required String path, required int duration}) async {
    if (duration > 0) {
      if (!isCancelSend) {
        widget.send(path, duration);
      } else {
        isCancelSend = false;
      }
    } else {
      showToast("说话时间太短!");
    }
  }

  @override
  dispose() {
    for (var subscription in subscriptions) {
      subscription.cancel();
    }
    super.dispose();
  }

  initRecordSound() {
    final responseSubscription = SoundPlayer.responseListener((recordResponse) {
      final status = recordResponse.msg;
      if (status == "onStop") {
        if (!isCancelSend) {
          final soundPath = recordResponse.path;
          final recordDuration = recordResponse.audioTimeLength;
          sendSound(path: soundPath!, duration: recordDuration!.ceil());
        }
      } else if (status == "onStart") {
        setState(() {
          isRecording = true;
        });
      } else {}
    });
    final amplitutdeResponseSubscription = SoundPlayer.responseFromAmplitudeListener((recordResponse) {
      final voiceData = double.parse(recordResponse.msg!);
      setState(() {
        if (voiceData > 0 && voiceData < 0.1) {
          voiceIcon = "images/voice_volume_2.png";
        } else if (voiceData > 0.2 && voiceData < 0.3) {
          voiceIcon = "images/voice_volume_3.png";
        } else if (voiceData > 0.3 && voiceData < 0.4) {
          voiceIcon = "images/voice_volume_4.png";
        } else if (voiceData > 0.4 && voiceData < 0.5) {
          voiceIcon = "images/voice_volume_5.png";
        } else if (voiceData > 0.5 && voiceData < 0.6) {
          voiceIcon = "images/voice_volume_6.png";
        } else if (voiceData > 0.6 && voiceData < 0.7) {
          voiceIcon = "images/voice_volume_7.png";
        } else if (voiceData > 0.7 && voiceData < 1) {
          voiceIcon = "images/voice_volume_7.png";
        } else {
          voiceIcon = "images/voice_volume_1.png";
        }
        if (overlayEntry != null) {
          overlayEntry!.markNeedsBuild();
        }
      });
    });
    subscriptions = [responseSubscription, amplitutdeResponseSubscription];
    SoundPlayer.initSoundPlayer();
    isInit = true;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (detail) async {
        if (!isInit) {
          bool hasMicrophonePermission = await XinDongPermissionCtr.checkPermission(XinDongAppPermission.microphone);
          bool hasStoragePermission = await XinDongPermissionCtr.checkPermission(XinDongAppPermission.audio);
          if (!hasMicrophonePermission || !hasStoragePermission) {
            return;
          }
          initRecordSound();
        }
      },
      onLongPressStart: onLongPressStart,
      onLongPressMoveUpdate: onLongPressUpdate,
      onLongPressEnd: onLongPressEnd,
      onLongPressCancel: onLonePressCancel,
      child: widget.buttons ??
          Container(
            height: 48,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              color: isRecording ? DZColors.downColor : DZColors.backgroundColor,
            ),
            child: const Row(
              children: [
                Expanded(
                  child: Text(
                    "按住说话", //'按住说话',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontWeight: FontWeight.w500,
                      fontSize: 15,
                      color: DZColors.titleColor,
                    ),
                  ),
                )
              ],
            ),
          ),
    );
  }
}
